package com.th.supcom.pds.impl.service.internal;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.carefx.fc.framework.web.gwt.util.FcUtils;
import net.carefx.framework.exception.BusinessException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import com.th.supcom.pds.domain.pojo.PdsSupplyPro;
import com.th.supcom.pds.domain.pojo.PhamDispensaryConfig;
import com.th.supcom.pds.domain.vo.PdsSupplyDetailVO;
import com.th.supcom.pds.impl.common.PdsConstants;
import com.th.supcom.pds.impl.common.enums.DeliveryType;
import com.th.supcom.pds.impl.common.enums.DispenseIndicator;
import com.th.supcom.pds.impl.manager.PdsSupplyDetailManager;
import com.th.supcom.pds.impl.manager.PdsSupplyProManager;
import com.th.supcom.pds.internal.api.DispenseDrugService;
import com.th.supcom.pds.internal.api.config.PhamDispensaryConfigService;
import com.th.supcom.pds.medicare.api.AdapterDrugManagerService;

/**
 * 核对发药业务服务实现类
 * 
 * @author 杨冲
 */
public class DispenseDrugServiceImpl implements DispenseDrugService
{
    private AdapterDrugManagerService m_adapterDrugManagerService;
    private PhamDispensaryConfigService m_phamDispensaryConfigService;
    private PdsSupplyProManager m_pdsSupplyProManager;
    private PdsSupplyDetailManager m_pdsSupplyDetailManager;

    public void setAdapterDrugManagerService (AdapterDrugManagerService adapterDrugManagerService)
    {

        this.m_adapterDrugManagerService = adapterDrugManagerService;
    }

    public void setPhamDispensaryConfigService (PhamDispensaryConfigService phamDispensaryConfigService)
    {

        this.m_phamDispensaryConfigService = phamDispensaryConfigService;
    }

    public void setPdsSupplyProManager (PdsSupplyProManager pdsSupplyProManager)
    {
        m_pdsSupplyProManager = pdsSupplyProManager;
    }

    public void setPdsSupplyDetailManager (PdsSupplyDetailManager pdsSupplyDetailManager)
    {
        m_pdsSupplyDetailManager = pdsSupplyDetailManager;
    }

    @Override
    public void dispenseDrug (List <PdsSupplyDetailVO> pdsPrescDetailVOs, String operator, String deptCode, String patientId)
    {
        s_logger.info ("调用 dispenseDrug (List <PdsPrescDetailCombine> pdsPrescDetailCombines = 【{}】", new Object[]
        { pdsPrescDetailVOs });
        // 重新从数据库获取最新的处方明细信息
        List <PdsSupplyPro> pdsSupplyPros = new ArrayList <PdsSupplyPro> ();
        for (PdsSupplyDetailVO pdsSupplyDetailVO : pdsPrescDetailVOs)
        {
            PdsSupplyPro pdsSupplyPro = new PdsSupplyPro ();
            pdsSupplyPro.setDispenseIndicator (DispenseIndicator.HasDispensed.getEnumCode ());
            pdsSupplyPro.setDispensingDatetime (FcUtils.getCurrentServerDateTimeForServer ());
            pdsSupplyPro.setUserIdDispensingProvider (operator);
            pdsSupplyPro.setSupplyId (pdsSupplyDetailVO.getSupplyId ());
            pdsSupplyPros.add (pdsSupplyPro);
        }
        List <PdsSupplyPro> list = m_pdsSupplyProManager.findPdsSupplyProListByList (pdsSupplyPros);
        // 检查发药状态，存在已发药记录给予提示信息
        if(checkDispenseStatus (list)) {
        	throw new BusinessException("处方已发药！");
        }
        // 更新批次信息
        m_pdsSupplyDetailManager.modifyPhamBatchNumberByList (pdsPrescDetailVOs);
        // 如果该处方中的所有明细都已被发药则将主处方改为已发药状态
        m_pdsSupplyProManager.modifyPdsSupplyProSortInfoByList (pdsSupplyPros);

        // 如果药房属性配置了在核对发药的时候出库，则进行药品出库
        if (needStockOutAtDispense (pdsPrescDetailVOs))
        {
            phamStockOut (pdsPrescDetailVOs, operator,deptCode,patientId);
        }
    }

    /**
     * 出库发药
     * 
     * @param list
     * @param operator
     */
    private void phamStockOut (List <PdsSupplyDetailVO> list, String operator,String deptCode,String patientId)
    {
        s_logger.info ("调用phamStockOut出库发药 (List <PdsSupplyDetailVO> list = 【{}】,operator:{}", new Object[]
        { list, operator });
        Map <String, Object> map = new HashMap <String, Object> ();
        map.put ("operator", operator);
        map.put("patientId", patientId);
        map.put("dispensaryCode", deptCode);
        m_adapterDrugManagerService.drugStockOut (list, map);
        // 更新医嘱状态接口。传入参数：医嘱ID，处方号，医嘱状态；返回参数：无。
        m_adapterDrugManagerService.sendStockOutInfo (list);
    }

    /**
     * 判断是否需要出库
     * 
     * @param list
     * @return
     */
    @Override
    public boolean needStockOutAtDispense (List <PdsSupplyDetailVO> list)
    {
        s_logger.info ("调用needStockOutAtDispense判断是否需要出库，参数信息:List <PdsSupplyDetailVO> list={}", new Object[]
        { list });
        // 获取药房配置，判断是否在此做出库操作
        PhamDispensaryConfig phamDispensaryConfig = new PhamDispensaryConfig ();
        phamDispensaryConfig.setPhamDispensaryCode (list.get (0).getPerformedBy ());
        List <PhamDispensaryConfig> configs = m_phamDispensaryConfigService.findPhamDispensaryConfigByExample (phamDispensaryConfig);
        if (configs.isEmpty ())
        {
            s_logger.info ("没有该执行科室");
            throw new BusinessException ("没有该执行科室");
        }
        if (DeliveryType.Check.getEnumCode ().equals (configs.get (0).getDeliveryType ()))
        {
            return true;
        }

        return false;
    }

    @Override
    public List <PdsSupplyDetailVO> getPhamBatchByExample (PdsSupplyDetailVO pdsPrescDetailCombine)
    {
        s_logger.info ("调用 dispenseDrug (PdsPrescDetailCombine pdsPrescDetailCombine = 【{}】", new Object[]
        { pdsPrescDetailCombine });
        List <PdsSupplyDetailVO> pdsPrescDetailCombines = null;
        try
        {
            /*
             * pdsPrescDetailCombines =
             * m_pdsPrescDetailManager.findPhamBatchByExample
             * (pdsPrescDetailCombine);
             */
        }
        catch (Exception e)
        {
            s_logger.error ("查询批次号出错，异常信息：", new Object[]
            { e });
            throw new BusinessException ("查询批次号出错" + PdsConstants.DEFALUT_HTML_WRAP + e.getLocalizedMessage (), e);
        }
        return pdsPrescDetailCombines;
    }

    /**
     * 检查处方是否已发药
     * 
     * @param pdsPresc
     * @return
     */
    private boolean checkDispenseStatus (List <PdsSupplyPro> pdsSupplyPros)
    {

        List <PdsSupplyPro> list = null;
        try
        {
            list = m_pdsSupplyProManager.findPdsSupplyProListByList (pdsSupplyPros);
        }
        catch (Exception e)
        {
            s_logger.error ("查找处方主记录出错" + e.getLocalizedMessage (), e);
            throw new BusinessException ("查找处方处方主记录出错" + PdsConstants.DEFALUT_HTML_WRAP + e.getLocalizedMessage (), e);
        }
        if (CollectionUtils.isEmpty (list))
        {
            return false;
        }

        for (PdsSupplyPro pdsSupplyPro : list)
        {
            if (DispenseIndicator.HasDispensed.getEnumCode ().equals (pdsSupplyPro.getDispenseIndicator ()))
            {
            	return true;
            }
        }
        return false;
    }

    /** 日志记录器. */
    public static final Logger s_logger = LoggerFactory.getLogger (DispenseDrugServiceImpl.class);

    /** 公司版权信息. */
    public static final String copyright = "Copyright 2014, XuNuo Corporation";

    /** 提交路径. */
    public static final String SCC_BRANCH = "$URL$";

    /** 提交日期. */
    public static final String SCC_LAST_MODIFICATION_DATE = "$Date$";

    /** 最终修改人员. */
    public static final String SCC_LAST_MODIFIER_NAME = "$Author$";

    /** 最终版本号. */
    public static final String SCC_REVISION = "$Revision$";

}
